package db

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var MongoClient *mongo.Client

// Mongo db 客户端
func init() {
	var err error
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	MongoClient, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	defer cancel()
}

func MongoCollection(c string) *mongo.Collection {
	col := MongoClient.Database("todo").Collection(c)
	col.Indexes().CreateOne(
		context.Background(),
		mongo.IndexModel{
			Keys: bson.M{
				"title": 1,
			},
			Options: options.Index().SetUnique(false),
		},
	)

	return col
}
